<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ page import="com.google.appengine.api.users.User"%>
<%@ page import="com.google.appengine.api.users.UserService"%>
<%@ page import="com.google.appengine.api.users.UserServiceFactory"%>
<%@ page import="au.org.htd.youslide.Background"%>
<%@ page isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link href="styles/template.css" rel="stylesheet" type="text/css" />
<link href="styles/homepage.css" rel="stylesheet" type="text/css" />
<link href="styles/mavdialog.css" rel="stylesheet" type="text/css" />
<script src="scripts/mootools-1.2.2-core.js" type="text/javascript"></script>
<script src="scripts/mootools-1.2.2.2-more.js" type="text/javascript"></script>
<script src="scripts/clientcide.js" type="text/javascript"></script>
<script src="scripts/json2.js" type="text/javascript"></script>
<script src="scripts/class.MavDialog.js" type="text/javascript"></script>
<title>youslide - <c:if test="${empty sessionScope.id}">create</c:if>
<c:if test="${not empty sessionScope.id}">edit</c:if></title>

<script type="text/javascript">
      var a = 'domready';
		  window.addEvent(a, function() {

      if(Browser.Engine.trident) { //IE
          var slideVar = new Fx.Slide($('slidable'), {
              mode: 'vertical',
              transition: 'sine:in', 
              duration: '500'
            }).hide().show().hide();
        } else {
          var slideVar = new Fx.Slide($('slidable'), {
            mode: 'horizontal', 
            transition: 'elastic:out',
            duration: '1500'
          }).hide().show().hide();
      }
		  slideVar.slideIn();
		 	
			$('save').addEvent('click', function(){
				if($('lyrics_form').backgroundId.value.length == 0) {
					$('random').fireEvent('click');
				}
				
				slideVar.slideOut().addEvent('onComplete', function(){
				  $("lyrics_form").submit();
        });
			});
		 
			$('discard').addEvent('click', function(){
				slideVar.slideOut().addEvent('onComplete', function(){
          history.go(-1);
        });
			});

	    var bgSlide1 = $('backgrounds');
	    bgSlide1.set('tween', {duration: '300'});

	    var left = 0;
      bgSlide1.tween('left', left+'px');
        
      $('prev').addEvent('click', function(){
        left += (0<=left?0:375);
    	  bgSlide1.tween('left', left+'px');
      });

      $('next').addEvent('click', function(){
        if($('backgrounds').getStyle('width').toInt()<=375-left) {
          if(limit >= thumbnails.length) return;
	        limit += 3;
	        getMoreThumbs();
        }
    	  left -= 375;
    	  bgSlide1.tween('left', left+'px');
      });

      function getMoreThumbs() {
        if(limit > thumbnails.length) {
          limit = thumbnails.length;
        }
        for(i=loaded+1; i<limit; i++) {
          getThumbs(i);
        }
        $$('#backgrounds .thumb_wrapper').addEvent('click', function() {
            tick(this);
        }); 
        new Tips.Pointy($$('#backgrounds .thumb_wrapper'));
      }

      var waiter;
      var new_bg;

      $('upload').addEvent('click', function(){
          new MavDialog.Prompt({
            'title': 'Attach a Background',
            'message': 'Enter URL',
            'force':true,
            'callback':function(url) {
                         if(null == url) { return };
								         new Request({
								           method: 'get',
								           url: '/upload',
								           data: { 'requestType':'image_url', 'url':url },
								           onRequest: function() {
								             limit = thumbnails.length;
								             getMoreThumbs();
								             var backgrounds = $("backgrounds");
								             var width = backgrounds.getStyle('width').toInt();
								             backgrounds.setStyle('width', width+125);
								             new_bg = new Element('div', {
								                 'id':'new_bg',
								                 'class':'thumb_wrapper'
								             }).inject(backgrounds);
 								
								             left = width+125<=375-left? left:-Math.floor(width/375)*375;
								             bgSlide1.tween('left', left);
 								            
 								             waiter = new Waiter(new_bg, {
								               containerProps: {
								                 styles: {
								                   position:'absolute',
								                   'text-align':'center',
								                   'margin-top':'35px'
								                  },
								                  'class':'waiterContainer'
								               }
								             });
								             waiter.start(); 
								           },
								           onComplete: function(response) {
								             new_bg.parentNode.removeChild(new_bg);
 								             thumbnails.push(response);
								             limit = thumbnails.length;
								             waiter.stop();
								             getMoreThumbs();
								           }
								         }).send();
                       }
        });
      });

      $('random').addEvent('click', function(){
    	  var index = Math.floor(Math.random()*thumbnails.length);
    	  var newLimit = Math.ceil((index+1)/3)*3;
        if(limit<newLimit) {
       	  limit = newLimit;
       	  getMoreThumbs();
       	  left = (3-limit)*125;
        } else {
          if(newLimit<3) newLimit=3;
          left = (3-newLimit)*125;
        }
        bgSlide1.tween('left', left);
    	  $(''+thumbnails[index]).fireEvent('click');
      });

      var thumbnails = JSON.parse("<%=Background.getBackgroundIds()%>");
      var length = thumbnails.length;
      var loaded = 0;
      var limit = 9;
      if(limit > length) {
          limit = length;
      }
      for(i=0; i<limit && i<length; i++) {
    	  getThumbs(i);
      }
      
      function getThumbs(key) {
        id = thumbnails[key];
        if(isNaN(id) || loaded==limit) return;
        
        var backgrounds = $("backgrounds");
        backgrounds.setStyle('width', backgrounds.getStyle('width').toInt()+125);
        var new_bg = new Element('div', {
            'id':id,
            'class':'thumb_wrapper',
            'rel':"Use this background"
        }).inject(backgrounds);
        new Element('img', {
            'src':"/download?requestType=thumbnail&id="+id,
            'top':'0px',
            'class':'thumbnail'
        }).inject(new_bg);
        new Element('div', {
        	  'class':'thumb_label',
        	  'text':key+1
        }).inject(new_bg);
        loaded=key;
      }

      function tick(el) {
        var selectedBg = $('lyrics_form').backgroundId;
        if("" != selectedBg.value && $(selectedBg.value+'tick')) {
          $(selectedBg.value+'tick').fade('out');
        }
        var tickId = el.id+'tick';
        if($(tickId)) {
          $(tickId).fade('in');
        } else {
          new Element('img', {
            'src':"/images/tick.png",
            'class':'tick',
            'id':tickId
          }).inject(el);
        }
        selectedBg.value = el.id; 
      }

      $$('#backgrounds .thumb_wrapper').addEvent('click', function() {
          tick(this);
      });

      new Tips.Pointy($$('#backgrounds .thumb_wrapper'));
      new Tips.Pointy($('upload'), {pointyTipOptions: {
    	    point: 7
        }
    	});
      new Tips.Pointy($('random'));

      $('englishLyrics').addEvent('change', function() {
          this.value = this.value.replace(/\n\n/g, "\n--------------------------------------\n");
      });

      $('chineseLyrics').addEvent('change', function() {
          this.value = this.value.replace(/\n\n/g, "\n--------------------------------------\n");
      });
      
      <c:if test="${not empty sessionScope.bgId}">
        var bg = $('<c:out value="${sessionScope.bgId}"/>');
	      if(!bg) {
	        getThumbs(<c:out value="${sessionScope.bgId}"/>)
	      }
	      bgSlide1.tween('left', (3-limit)*125);
	      bg.fireEvent('click');
      </c:if>
		});

	  </script>
</head>

<body>
<div id="masthead"><a href="index.jsp" id="branding"> <img
	src="images/logo.jpg" alt="youSlide" border="0" /> </a> <%
    UserService userService = UserServiceFactory.getUserService();
 			User user = userService.getCurrentUser();
 			if (user != null) {
 %>
<div id='welcome'>Welcome, <%=user.getNickname()%> (<a
	href="<%=userService.createLogoutURL(request.getRequestURI())%>">Sign
out</a>)</div>
<%
   } else {
%> <script type="text/javascript">location.href='index.jsp'</script> <%
    }
 %>
</div>
<div id="wrapper" class="funbg">
<div id="slidable">
<h1><c:if test="${empty sessionScope.id}">Create: </c:if> <c:if
	test="${not empty sessionScope.id}">Edit: </c:if>
</title>
<c:out value="${sessionScope.englishName}" /> <c:if
	test="${not empty sessionScope.englishName}">
	<c:if test="${not empty sessionScope.chineseName}"> | </c:if>
</c:if> <c:out value="${sessionScope.chineseName}" /></h1>

<form name="lyrics_form" id="lyrics_form" method="post"
	action="/slides?requestType=save"><input type="hidden" name="id"
	value='<c:out value="${sessionScope.id}"/>' /> <input type="hidden"
	name="englishName" value='<c:out value="${sessionScope.englishName}"/>' />
<input type="hidden" name="chineseName"
	value='<c:out value="${sessionScope.chineseName}"/>' /> <input
	type="hidden" name="backgroundId" value='' /> <c:if
	test="${empty sessionScope.id}">
	<TEXTAREA NAME="englishLyrics" id="englishLyrics"
		onblur="if (this.value == '') { this.value = this.defaultValue; }"
		onfocus="if (this.value == this.defaultValue) { this.value = ''; }">English lyrics</TEXTAREA>
	<TEXTAREA NAME="chineseLyrics" id="chineseLyrics"
		onblur="if (this.value == '') { this.value = this.defaultValue; }"
		onfocus="if (this.value == this.defaultValue) { this.value = ''; }">Chinese lyrics</TEXTAREA>
</c:if> <c:if test="${not empty sessionScope.id}">
	<TEXTAREA NAME="englishLyrics" id="englishLyrics"><c:out
		value="${sessionScope.englishLyrics}" /></TEXTAREA>
	<TEXTAREA NAME="chineseLyrics" id="chineseLyrics"><c:out
		value="${sessionScope.chineseLyrics}" /></TEXTAREA>
</c:if>

<div id="previewcontrols"><input id="prev" type="button" />
<div id="backgrounds_wrapper">
<div id="backgrounds" style="width: 0px"></div>
</div>
<input id="next" type="button" /> <input id="upload" type="button"
	rel="Upload a background" /> <input id="random" type="button"
	rel="Randomly pick a background" /></div>
<div id="buttons"><input id="save" class="submit" type="button" />
<br>
<input id="discard" class="submit" type="button" /></div>
</form>
</div>
</div>
<div id="upload_form_wrapper">
<form name="upload_form" id="upload_form" method="get"
	' action="/upload">Upload a new background<br>
<br>
<input name="requestType" value="url" type="hidden" /></form>
</div>
</body>
</html>
